<template>
  <div style="height: 100%;width: 100%;" v-loading="showLoading&&loading">
    <!--    <div id="tb_tableTxt_Container" style="height: 100%" v-if="workBook.chartMode===6">-->
    <!--      <table id="tb_tableTxt" style="height: 100%"></table>-->
    <!--    </div>-->

    <component v-if="workBook&&workBook.chartMode" ref='chartInstance' :is="dynamicComponentName"
               :workBook="workBook"></component>
    <!--    <div id="chart" style="height: 100%;width: 100%;" ></div>-->
  </div>
</template>

<script>
import {computed, nextTick, onMounted, onUnmounted, reactive, ref, toRefs, watch} from 'vue';
import {store as shared} from "@/components/chart/common/store";
import {getWorkBook, loadData, parseToObj} from "@/api/workBook";
import {getDataSource} from "@/api/dataSource";
import {changeTone} from "@/components/chart/common/config";
import {ElMessage} from "element-plus";
import VueEcharts from '@/components/chart/vueEcharts'
import IndicatorStickers from "@/components/chart/IndicatorStickers"
import dvChart from "@/components/chart/dvChart";

export default {
  name: "workBookView",
  components: {
    VueEcharts,
    IndicatorStickers,
    dvChart
    // VueEcharts: defineAsyncComponent(() =>
    //   import('@/components/chart/vueEcharts')
    // ),
    // IndicatorStickers: defineAsyncComponent(() =>
    //   import("@/components/chart/IndicatorStickers")
    // )
  },
  props: {
    workBookId: String,
    dashboardItem: Object,
    parentItem: Object,
    currentWorkBook: Object,
    dashboard: Object
  },
  emits: ['initFinished'],
  setup(props, context) {
    const {workBookId, dashboardItem, parentItem, dashboard} = toRefs(props);
    const chartInstance = ref({})
    const state = reactive({
      workBook: props.currentWorkBook,
      dataSource: {},
      timer: {},
      currentEditChart: {},
      data: [],  //缓存数据
      loading: false, //加载状态
      showLoading: true, //是否显示loading
      shared: shared
    })
    const loadWorkBook = async () => {
      if (workBookId.value) {
        let workBookResp = await getWorkBook(workBookId.value);
        state.workBook = parseToObj(workBookResp.data);
        if (workBookResp.data) {
          state.dataSource = await getDataSource(workBookResp.data.dataSourceId);
          getData()
        } else {
          ElMessage.error("没有找到对应的图表，请检查参数是否正确：" + workBookId.value)
        }
      }
    }
    const dynamicComponentName = computed(() => {
      if (state.workBook.chartMode === 19) {
        return 'IndicatorStickers'
      } else if (state.workBook.chartMode === 6 || state.workBook.chartMode === 16 || state.workBook.chartMode === 18 || state.workBook.chartMode === 22) {
        return 'dvChart'
      } else {
        return 'VueEcharts'
      }
    })
    //分析界面请求数据
    const getData = (showLoading) => {
      if (showLoading) {
        state.loading = true
      }
      if (state.workBook.id && state.dataSource.id) {
        //设置下钻参数
        if (parentItem && parentItem.value) {
          const param = parentItem.value.param
          if (parentItem.value.workbook.dataSourceId === state.workBook.dataSourceId) {
            const filter = parentItem.value.workbook.filters;
            state.workBook.filters.forEach(t => {
              const currentFilter = filter.find(f => f.field.name == t.field.name);
              if (currentFilter) {
                Object.assign(t, currentFilter)
              }
            })
            param.forEach(currentParam => {
              const currentParamFilter = state.workBook.filters.find(t => t.field.systemName === currentParam.field.systemName);
              if (currentParamFilter) {
                currentParamFilter.matchValue = currentParam.value[0]
              } else {
                state.workBook.filters.push({
                  filterMode: 1,
                  field: currentParam.field,
                  filterItems: currentParam.value
                })
              }
            })
          }
        }

        loadData(state.workBook, state.dataSource, showLoading, dashboard && dashboard.value.isQueue).then(data => {
          if (state.currentEditChart && state.currentEditChart.update) {
            state.currentEditChart.update(data);
          } else {
            //刷新图表
            // nextTick(()=>{
            refreshChart(state.workBook, data)
            // })
          }
        }).finally(() => {
          state.loading = false;
        })
      }
    }

    //刷新图表
    const refreshChart = (workBook, data) => {

      if (!workBook.chartMode || !data || !data[0]) {
        return false;
      }

      state.data = data;

      state.workBook = workBook;

      let _currentChartMode = workBook.chartMode

      //处于自动更新数据的状态
      if (state.timer && workBook.autoUpdate > 0 && state.currentEditChart) {
        clearTimeout(state.timer);
        state.timer = setTimeout(() => {
          getData(false)
        }, workBook.autoUpdate * 60 * 1000);
        if (state.currentEditChart.update) {
          state.currentEditChart.update(data);
          return false;
        }
      }

      removeChart();

      const columnFields = workBook.columns;
      const rowFields = workBook.rows;

      //构建图表
      nextTick(() => {
        chartInstance.value.build(data, columnFields, rowFields, _currentChartMode, {
          subDimension: workBook.subDimension,
          scale: 1,
          isYoy: workBook.isYoy,
          rankMark: {},
          gauge: {},
          chartConfig: workBook.chartConfig,
          autoUpdate: workBook.autoUpdate,
          dataMarking: workBook.dataMarking
        }).then(currentChart => {
          state.currentEditChart = currentChart
          if (!state.currentEditChart) {
            return false;
          }
          if (dashboardItem && dashboardItem.value) {
            dashboardItem.value.workbook = workBook
            context.emit('initFinished', state.currentEditChart, dashboardItem.value, workBook)
            dashboardItem.value.currentEditChart = state.currentEditChart
          }
          //自动刷新
          if (workBook.autoUpdate > 0 && !state.timer) {
            state.showLoading = false;
            state.timer = setTimeout(() => {
              getData()
            }, workBook.autoUpdate * 1000);
          }
        })
      })


    }

    onMounted(loadWorkBook);

    watch(workBookId, () => {
      removeChart()
      state.currentEditChart = null
      state.workBook = {}
      loadWorkBook();
    })

    onUnmounted(() => {
      if (state.timer) {
        clearInterval(state.timer)
      }
      removeChart();
    })
    //销毁图表实例
    const removeChart = () => {
      if (state.currentEditChart && state.currentEditChart.removeChart) {
        state.currentEditChart.removeChart();
      }
    }
    return {
      refreshChart,
      getData,
      ...toRefs(state),
      removeChart,
      chartInstance,
      dynamicComponentName,
    }
  },
  watch: {
    'shared.darkMode'() {
      if (this.workBook.chartMode) {
        changeTone(this.workBook)
        this.refreshChart(this.workBook, this.data);
      }
    },
    'shared.enableDecal'() {
      this.refreshChart(this.workBook, this.data);
    },
    'shared.runHash'() {
      if (shared.globalFilter) {
        //全局筛选
        this.workBook.globalFilter = shared.globalFilter
      }
      this.getData(shared.dashboard);
    }
  }
}
</script>

<style scoped>
</style>
